/* 
	Copyright 2012 Atif Farrukh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.*/
package com.atiffarrukh.get.inspired;

import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SmShare extends Activity implements OnClickListener {

	Button bAddFromPeople,bSend,bCancel;
	EditText eNumber,eBody;
	Context context;
	Bundle b;
	String quote,msg;
	
	private static final int PICK_CONTACT = 0;
	private static final String TAG = "SmShareActivity";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate()");
		setContentView(R.layout.activity_sm_share);
		Log.d(TAG, "setContentView");
		bAddFromPeople = (Button) findViewById(R.id.bAdd);
		bSend = (Button) findViewById(R.id.bSend);
		bCancel = (Button) findViewById(R.id.bCancel);
		eNumber = (EditText) findViewById(R.id.etNumber);
		eBody = (EditText) findViewById(R.id.etBody);
		Log.d(TAG, "Initializes componen");
		/*AlertDialog.Builder smsShareDialog = new AlertDialog.Builder(context);
		create = smsShareDialog.create();
		LayoutInflater layout = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		create.setTitle("Inspire your friends");
		View body = layout.inflate(R.layout.activity_sm_share, null);
		create.setView(body);
		//alert.setIcon(R.drawable.ic_action_search);
		create.show();*/

		Log.d(TAG, "Initialized componen");
		
		bSend.setOnClickListener(this);
		bCancel.setOnClickListener(this);
		bAddFromPeople.setOnClickListener(this);

		msg = "";
		Log.d(TAG, "getting Bundle");
		b = getIntent().getExtras();
		quote = "\n " + b.getString("postValue");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.bAdd){
			Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
			startActivityForResult(intent, PICK_CONTACT);
		}else if (v.getId() == R.id.bSend) {
			if(eNumber.getText().toString().equals("") || eNumber.getText().toString().equals(null)){
				Toast.makeText(this, "Please enter number", Toast.LENGTH_LONG).show();
			}else{
				sendSMS(eNumber.getText().toString(),eBody.getText().toString() + quote);
				storeMessage(eNumber.getText().toString(),eBody.getText().toString() + quote);
				eBody.setText("");
				//create.dismiss();
				goBack();	
			}
		} else if(v.getId() == R.id.bCancel){
			goBack();
		}
	}

	private void goBack() {
		// TODO Auto-generated method stub
		finish();

	}

	private void storeMessage(String phoneNumber2, String message) {
		// TODO Auto-generated method stub
		ContentValues values = new ContentValues();
		values.put("address", phoneNumber2);
		values.put("body",message);
		getContentResolver().insert(Uri.parse("content://sms/sent"), values);
	}

	private void sendSMS(String phoneNumber, String message) {
		// TODO Auto-generated method stub
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		/* PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
	        new Intent(SENT), 0);

	    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
	        new Intent(DELIVERED), 0);
		 */


		//---when the SMS has been sent---
		registerReceiver(new BroadcastReceiver(){
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS sent", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Generic failure", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "No service", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off", 
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(SENT));

		//---when the SMS has been delivered---
		registerReceiver(new BroadcastReceiver(){
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS delivered", 
							Toast.LENGTH_SHORT).show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "SMS not delivered", 
							Toast.LENGTH_SHORT).show();
					break;                        
				}
			}
		}, new IntentFilter(DELIVERED));        

		SmsManager sms = SmsManager.getDefault();
		ArrayList<String> parts = sms.divideMessage(message);

		ArrayList<PendingIntent> sentPI = new ArrayList<PendingIntent>();
		for (int i=0; i < parts.size(); i++){

			PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(SENT), PendingIntent.FLAG_CANCEL_CURRENT);
			sentPI.add(pi);
		}

		ArrayList<PendingIntent> deliveredPI = new ArrayList<PendingIntent>();
		for (int i=0; i < parts.size(); i++){

			PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(SENT), PendingIntent.FLAG_CANCEL_CURRENT);
			deliveredPI.add(pi);
		}
		sms.sendMultipartTextMessage(phoneNumber, null, parts, sentPI, deliveredPI);  

	}
	
	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);

		switch (reqCode) {
		case (PICK_CONTACT) :
			if (resultCode == Activity.RESULT_OK) {
				String contactId = ""; 
				String phoneNumber = "";
				Uri contactData = data.getData();
				Cursor cur = managedQuery(contactData, null, null, null, null);
				ContentResolver contect_resolver = getContentResolver();

				if (cur.moveToFirst()) {
					String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
					String name = "";
					//String no = "";

					Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);

					if (phoneCur.moveToFirst()) {
						name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
						contactId = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					}

					Log.e("Phone no & name :***: ", name + " : " + contactId);
		
				}
				
				Log.d("Contact Id", contactId + " " );
				eNumber.setText(contactId);		

			}
		break;
		}
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}
}



